package com.example.wm.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.example.wm.common.Result;
import com.example.wm.common.ResultData;

import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/Imgupload")
public class Imgupload {
    @Value("${upload.path}")
    private String uploadPath;
    @PostMapping("/proxyUpload2")
    public Result proxyUpload2(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return ResultData.error(304, "文件为空,请选择一张图片上传");
        }

        // 确保上传目录存在
        File dir = new File(uploadPath);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                return ResultData.error(500, "上传目录创建失败");
            }
        }

        // 获取文件扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            return ResultData.error(304, "文件名无效");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 使用时间戳生成新的文件名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String newFilename = timestamp + fileExtension;

        // 构建文件保存路径
        Path filePath = Paths.get(uploadPath, newFilename);

        // 保存文件到本地
        try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
            fos.write(file.getBytes());
        } catch (IOException e) {
            return ResultData.error(500, "文件上传失败,请稍后再试");
        }

        // 构建返回的URL
        String fileUrl = "" + filePath.getFileName();

        // 返回成功结果
        return ResultData.success(fileUrl);
    }

    @PostMapping("/proxyUpload")
    public Result proxyUpload(@RequestParam("file") MultipartFile file) {
//        System.out.println(file+"file");
        if (file == null || file.isEmpty()) {
            return ResultData.error(304, "文件为空,请选择一张图片上传");
        }
        String filename = file.getOriginalFilename();
        if (filename == null || filename.trim().isEmpty()) {
            return ResultData.error(305, "文件名为空");
        }
        // 可选:校验文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ResultData.error(306, "仅支持图片类型文件上传");
        }

        OkHttpClient client = new OkHttpClient();

        RequestBody fileBody;
        try {
            fileBody = RequestBody.create(file.getBytes(), MediaType.parse(contentType));
        } catch (Exception e) {
            return ResultData.error(500, "读取文件内容失败: " + e.getMessage());
        }

        MultipartBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", filename, fileBody)
                .build();

        Request request = new Request.Builder()
                .url("http://118.31.75.80:8050/ours/saveFile")
                .post(requestBody)
                .build();


        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String respStr = response.body() != null ? response.body().string() : "";
                // 先解析外层
                JSONObject outer = JSON.parseObject(respStr);
                String innerStr = outer.getString("data");

                return ResultData.success(innerStr);
            } else {
                return ResultData.error(500, "转发上传失败: " + response.message());
            }
        } catch (Exception e) {
            return ResultData.error(500, "转发上传失败: " + e.getMessage());
        }
    }
    @PostMapping("/uploadBase64")
    public Result uploadBase64(@org.springframework.web.bind.annotation.RequestBody Map<String, String> requestData) {
        try {
            String base64Data = requestData.get("base64Data");
            String fileName = requestData.get("fileName");

            if (base64Data == null || base64Data.isEmpty()) {
                return ResultData.error(304, "数据为空");
            }

            System.out.println("=== 开始转发Base64文件上传 ===");
            System.out.println("接收到的文件名: " + fileName);
            System.out.println("Base64数据长度: " + base64Data.length());

            // 直接转发到远程服务器
            OkHttpClient client = new OkHttpClient();

            // 准备请求数据
            Map<String, String> remoteRequestData = new HashMap<>();
            remoteRequestData.put("base64Data", base64Data);
            remoteRequestData.put("fileName", fileName);

            // 转换为JSON
            String jsonData = new ObjectMapper().writeValueAsString(remoteRequestData);

            RequestBody body = RequestBody.create(jsonData, MediaType.parse("application/json"));
            Request request = new Request.Builder()
                    .url("http://118.31.75.80:8050/ours/uploadBase64")
                    .post(body)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                System.out.println("远程服务器响应状态: " + response.code());

                if (response.isSuccessful()) {
                    String respStr = response.body() != null ? response.body().string() : "";
                    System.out.println("远程服务器响应: " + respStr);

                    // 解析远程服务器响应，提取文件名
                    JSONObject outer = JSON.parseObject(respStr);
                    String innerStr = outer.getString("data");

                    // 直接返回文件名
                    return ResultData.success(innerStr);
                } else {
                    String errorBody = response.body() != null ? response.body().string() : "";
                    System.out.println("远程服务器错误: " + errorBody);
                    return ResultData.error(500, "转发上传失败: " + response.message());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.error(500, "转发上传失败: " + e.getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error(500, "处理失败: " + e.getMessage());
        }
    }


    @PostMapping("/uploadBase642")
    public Result uploadBase642(@org.springframework.web.bind.annotation.RequestBody Map<String, String> requestData) {
        try {
            String base64Data = requestData.get("base64Data");
            String fileName = requestData.get("fileName");

            if (base64Data == null || base64Data.isEmpty()) {
                return ResultData.error(304, "数据为空");
            }

            System.out.println("=== 开始处理Base64文件上传 ===");
            System.out.println("接收到的文件名: " + fileName);
            System.out.println("Base64数据长度: " + base64Data.length());

            // 移除Base64前缀（如果有的话）
            String actualData = base64Data;
            String contentType = "image/jpeg"; // 默认类型

            if (base64Data.contains(",")) {
                String prefix = base64Data.substring(0, base64Data.indexOf(","));
                actualData = base64Data.substring(base64Data.indexOf(",") + 1);

                // 从前缀中检测文件类型
                if (prefix.contains("image/png")) {
                    contentType = "image/png";
                } else if (prefix.contains("image/jpeg") || prefix.contains("image/jpg")) {
                    contentType = "image/jpeg";
                } else if (prefix.contains("image/gif")) {
                    contentType = "image/gif";
                } else if (prefix.contains("image/webp")) {
                    contentType = "image/webp";
                }

                System.out.println("检测到的文件类型: " + contentType);
                System.out.println("移除前缀后的数据长度: " + actualData.length());
            }

            // 解码Base64数据
            byte[] fileBytes = java.util.Base64.getDecoder().decode(actualData);
            System.out.println("解码后的文件大小: " + fileBytes.length + " 字节");

            // 验证文件大小（可选）
            if (fileBytes.length > 10 * 1024 * 1024) { // 10MB限制
                return ResultData.error(413, "文件大小超过限制（最大10MB）");
            }

            // 确保上传目录存在
            File dir = new File(uploadPath);
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    return ResultData.error(500, "上传目录创建失败");
                }
            }

            // 获取文件扩展名
            String fileExtension = ".jpg"; // 默认扩展名
            if (contentType.equals("image/png")) {
                fileExtension = ".png";
            } else if (contentType.equals("image/gif")) {
                fileExtension = ".gif";
            } else if (contentType.equals("image/webp")) {
                fileExtension = ".webp";
            }

            // 使用时间戳生成新的文件名（与saveFile保持一致）
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String newFilename = timestamp + fileExtension;

            // 构建文件保存路径
            Path filePath = Paths.get(uploadPath, newFilename);

            // 保存文件到本地
            try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
                fos.write(fileBytes);
            } catch (IOException e) {
                return ResultData.error(500, "文件上传失败，请稍后再试");
            }

            // 构建返回的URL（与saveFile保持一致）
            String fileUrl = "" + filePath.getFileName();

            // 返回成功结果（与saveFile保持一致）
            return ResultData.success(fileUrl);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ResultData.error(400, "Base64数据格式错误: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error(500, "处理失败: " + e.getMessage());
        }
    }
    @PostMapping("/deleteimg2")
    private Result deleteimg2(@org.springframework.web.bind.annotation.RequestBody List<String> list) throws MalformedURLException {
        boolean allDeleted = true;
        StringBuilder errorMessages = new StringBuilder();
        for (String s : list) {
            // URL url = new URL(s);
            // String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') +
            // 1);
            // System.out.println( fileName+"fileName" );
            File file = new File(uploadPath, s);

            if (file.exists()) {
                if (!file.delete()) {
                    allDeleted = false;
                    errorMessages.append("文件 ").append(s).append(" 删除失败; ");
                }
            } else {
                allDeleted = false;
                errorMessages.append("文件 ").append(s).append(" 不存在; ");
            }
        }

        if (allDeleted) {
            return ResultData.success("所有文件删除成功");
        } else {
            return ResultData.error(304, errorMessages.toString());
        }
    }

    @PostMapping("/deleteimg")
    public Result deleteImages(@org.springframework.web.bind.annotation.RequestBody List<String> list) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        HttpEntity<List<String>> request = new HttpEntity<>(list, headers);
        RestTemplate restTemplate = new RestTemplate();

        // 发送 POST 请求
        String response = restTemplate.postForObject("http://118.31.75.80:8050/ours/deleteimg", request, String.class);

        // 处理响应
        if (response != null) {
            System.out.println("服务器响应: " + response);
            return ResultData.success(response);
        } else {
            System.out.println("没有收到服务器响应");
            return ResultData.error(304, "删除失败");
        }
    }


}
